import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Set;

public class AutoTest02 {
    WebDriver driver = null;
    void createDriver()
    {
        //1. 打开浏览器 使用驱动来打开
        WebDriverManager.chromedriver().setup();
        //增加浏览器配置：创建驱动对象要强制指定允许访问所有的链接
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        //设置无头模式:测试是在后台运行,不会看到对浏览器进行的操作
//        options.addArguments("--headless");
        //设置浏览器的加载策略:
        //Normal:说有元素加载完,才向下执行,最慢
        options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
        //eager:必要元素加载出来就向下执行
        //none:执行完该命令,就立即向下执行.最快

        driver = new ChromeDriver(options);
//        driver.get("https://www.baidu.com");
        driver.get("https://www.baidu.com/s?rsv_idx=1&tn=15007414_20_dg&wd=%E6%B2%B3%E5%B8%88%E5%A4%A7&fenlei=256&usm=6&ie=utf-8&base_query=%E6%B2%B3%E5%B8%88%E5%A4%A7&tag_key=%E5%85%A8%E9%83%A8&rsv_dl=re_dl_tag_1&rsv_pq=a84c6de20009042d&oq=%E6%B2%B3%E5%B8%88%E5%A4%A7&rsv_t=95b1Tg4g%2F8JowduKdtS9TEvXVL8AoLR2M%2FLhxWaaejfTSBtSfAwj6Y8Tnrhs6nh9QRUf0%2F8");
    }

    //测试百度搜索关键词；迪丽热巴
    public void test01() throws InterruptedException {

        createDriver();
        //2. 输入完整的网址：https://www.baidu.com

        Thread.sleep(3000);

        //3. 找到输入框，并输入关键词：迪丽热巴
        driver.findElement(By.cssSelector("#kw")).sendKeys("迪丽热巴");
        Thread.sleep(3000);

        //4. 找到百度一下按钮，并点击
        driver.findElement(By.cssSelector("#su")).click();
        Thread.sleep(3000);

        //5. 关闭浏览器
        driver.quit();
    }

    public void test02() throws InterruptedException {
        createDriver();
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).sendKeys("杨洋");
        Thread.sleep(1000);
        driver.findElement(By.xpath("//*[@id=\"su\"]")).click();
        Thread.sleep(1000);
        driver.close();
    }

    public void test03() throws InterruptedException {
        createDriver();
        driver.findElement(By.xpath("//*[@id=\"hotsearch-content-wrapper\"]/li[1]/a/span[2]")).click();
        Thread.sleep(3000);
        driver.close(); 
    }

    public void test04() throws InterruptedException {
        createDriver();
//        //获取元素集合
//        List<WebElement> l = driver.findElements(By.cssSelector("#hotsearch-content-wrapper > li > a > span.title-content-title"));
//        for(int i=0;i<l.size();i++){
//            System.out.println(l.get(i).getText());
//        }
//        Thread.sleep(10000);

//        //获取文本信息
//        String text1 = driver.findElement(By.cssSelector("#hotsearch-content-wrapper > li:nth-child(2) > a > span.title-content-title")).getText();
//        System.out.println("text1:"+text1);
//        String text = driver.findElement(By.cssSelector("#su")).getAttribute("value");
//        System.out.println("百度按钮: "+text);
//
//        /**
//         * 2.5 获取当前⻚⾯标题
//         * getTitle()
//         * 2.6获取当前⻚⾯URL
//         * getCurrentUrl()
//         */
//        String title = driver.getTitle();
//        System.out.println(title);
//        String url = driver.getCurrentUrl();
//        System.out.println(url);

//        /**
//         * 3.1 切换窗⼝
//         * 1）获取当前⻚⾯句柄：
//         * driver.getWindowHandle();
//         * 3）获取所有⻚⾯句柄：
//         * driver.getWindowHandles()
//         * 3）切换当前句柄为最新⻚⾯
//         */
//        String windowHandle = driver.getWindowHandle();
//        System.out.println("切换前页面句柄: "+windowHandle);
//        //点击"贴吧",进入新的页面
//        String text = driver.findElement(By.cssSelector("#s-top-left > a:nth-child(6)")).getText();
//        System.out.println("打印贴吧: "+text);
//        driver.findElement(By.cssSelector("#s-top-left > a:nth-child(6)")).click();
//        Thread.sleep(2000);
//        //获取所有页面句柄
//        Set<String> windowHandles = driver.getWindowHandles();
//        System.out.println("获取到的所有句柄");
//        System.out.println(windowHandles);
//        for(String s:windowHandles){
//            if(!windowHandle.equals(s)){
//                //切换当前页面的句柄:
//                driver.switchTo().window(s);
//            }
//        }
//        String windowHandle1 = driver.getWindowHandle();
//        System.out.println("切换后页面句柄:"+windowHandle1);

        /**
         * 窗⼝的⼤⼩设置
         */
        //窗口最大化:
        driver.manage().window().maximize();
        Thread.sleep(1000);
        //窗口最小化:
        driver.manage().window().minimize();
        Thread.sleep(1000);
        //全屏:
        driver.manage().window().fullscreen();
        Thread.sleep(1000);
        //自定义大小:
        driver.manage().window().setSize(new Dimension(1024,1024));
        Thread.sleep(1000);

        driver.close();
        driver.quit();
    }

    public void test05() throws IOException, InterruptedException {
        createDriver();

//        //获取屏幕截图:
//        driver.findElement(By.cssSelector("#s-top-left > a:nth-child(6)")).click();
//        Thread.sleep(1000);
//        String windowHandle = driver.getWindowHandle();
//        Set<String> windowHandles = driver.getWindowHandles();
//        for(String s:windowHandles){
//            if(!windowHandle.equals(s)){
//                driver.switchTo().window(s);
//            }
//        }
//        //获取屏幕截图:以文件形式存储:
//        //注意,这里的截图是针对指定的页面截图的,而不失当前所显示的页面,要看driver的句柄是哪个:
//        File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//        FileUtils.copyFile(file,new File("my.png"));

        //获取大量屏幕截图
        String windowHandle = driver.getWindowHandle();
        getPath(getClass().getName());
        driver.findElement(By.cssSelector("#s-top-left > a:nth-child(6)")).click();
        Set<String> windowHandles = driver.getWindowHandles();
        for(String s:windowHandles){
            if(!s.equals(driver.getWindowHandle())){
                driver.switchTo().window(s);
            }
        }
//        Thread.sleep(2000);
        getPath(getClass().getName());
        driver.close();
        Thread.sleep(3000);
        driver.switchTo().window(windowHandle);
        driver.quit();
    }
    private void getPath(String name) throws IOException {
        //⽣成的⽂件夹路径./src/test/autotest-2022-08-01/goodsbroser-20220801-214130.png
        SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat s2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = s1.format(System.currentTimeMillis());
        String fileTime = s2.format(System.currentTimeMillis());

        String fileName = "./src/test/image/"+dirTime+"/"+name+"-"+fileTime+".png";
        System.out.println("fileName: "+fileName);
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //将截图放到制定文件中:
        FileUtils.copyFile(src,new File(fileName));
    }

    /**
     * 等待:
     * 强制等待 Thread.sleep()方法调用的等待
     * 隐式等待 :智能等待,在规定的时间内查找元素,找到了直接向下执行,不会继续等待;找不到就抛出异常
     *      作用在调用隐式命令后的全局作用域,
     * 显示等待:对指定元素的指定条件进行查找,在执行时间内找到了就继续向下执行,找不到就抛出异常
     *          作用在当前元素
     */
    public void test06() throws InterruptedException {
        createDriver();
        driver.findElement(By.cssSelector("#kw")).sendKeys("杨洋");
        driver.findElement(By.cssSelector("#su")).click();
//        driver.findElement(By.cssSelector("#\\31  > div > div > div > div > div > div.false > div.ps-header-wrapper_59GAF.header-wrapper_5npvH > div.cos-row.row-text_3Un8U.row_1inPx > div > div > div.cos-flex.cos-items-center > div.title-wrapper_XLSiK > a > div > p > span > span"));

        Thread.sleep(1000);
        driver.findElement(By.cssSelector("#kw")).clear();
        driver.findElement(By.cssSelector("#kw")).sendKeys("河师大");
        driver.findElement(By.cssSelector("#su")).click();
        Thread.sleep(3000);
        String text = driver.findElement(By.cssSelector("#\\31  > div > div > div.cosc-card-content > div.cos-space-mt-sm.cos-flex > p > span.cos-tag.cos-sm.cos-tag-filled.cos-space-mr-xs.cos-color-text-on-primary-light.cos-color-bg-primary-light")).getText();
//        driver.findElement(By.cssSelector("#\\31  > div > div > div.cosc-card-content > div.cos-link.cos-block.new-header_4yNlb > div > div.header-detail_63RMj > div"))
        System.out.println("河师大:"+text);

        driver.quit();
    }

    void test07(){
        createDriver();
        //隐式等待3秒
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(3));
        driver.findElement(By.cssSelector("#kw")).sendKeys("杨洋");
        driver.findElement(By.cssSelector("#su")).click();

        driver.findElement(By.cssSelector("#kw")).clear();
        driver.findElement(By.cssSelector("#kw")).sendKeys("河师大");
        driver.findElement(By.cssSelector("#\\31  > div > div > div.cosc-card-content > div.cos-link.cos-block.new-header_4yNlb > div > div.header-detail_63RMj > a"));
        driver.quit();
    }

    void test08(){
        createDriver();
        //隐式等待设置10s:
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(3));
        //显示等待:
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
//        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#su")));
//        driver.findElement(By.cssSelector("#kw")).click();
        //隐式显示 混合使用


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        System.out.println("查找之前: "+simpleDateFormat.format(System.currentTimeMillis()));
        //查找一个找不到的元素:
        try{
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#s-hotsearch-wrapper > div > a.hot-title > div > img")));
            System.out.println(driver.findElement(By.cssSelector("#s-hotsearch-wrapper > div > a.hot-title > div > img")).getText());
        }catch (TimeoutException e){
            System.out.println("元素不存在");
        }
        System.out.println("查找之后: "+simpleDateFormat.format(System.currentTimeMillis()));
        driver.quit();
    }
    /**
     * 浏览器导航:
     * 浏览器的前进、后退、刷新
     */
    public void test09() throws InterruptedException {
        createDriver();
        driver.findElement(By.cssSelector("#searchTag > div > div > a:nth-child(2) > span")).click();
        Thread.sleep(3000);
        //后退:
        driver.navigate().back();
        Thread.sleep(3000);
        //前进
        driver.navigate().forward();
        Thread.sleep(3000);
        //刷新
        driver.navigate().refresh();
        Thread.sleep(3000);

        driver.quit();
    }

    /**
     * 弹窗:
     */
    public void test10(){
        createDriver();


    }
}
